package net.pws.oos.web;

import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.pws.oos.security.SecurityUtils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.octo.captcha.service.image.ImageCaptchaService;
import javax.imageio.*;

@Controller
public class IndexAction {
    
    @Autowired
    private ImageCaptchaService jcaptchaService;
    
    @RequestMapping("/biz/welcome.do")
    public String welcome(HttpServletRequest request, HttpServletResponse response) throws IOException {
    	String ctx = request.getContextPath();
        String redirectUri = ctx + "/index.jsp";
        if (SecurityUtils.allowedResource(SecurityUtils.RES_TASK_MAP)) {
            redirectUri = ctx + "/biz/task/map.do";
        }
        else if (SecurityUtils.allowedResource(SecurityUtils.RES_TASK_SELF)) {
            redirectUri = ctx + "/biz/task/selves.do";
        } else {
        	RuntimeException e = new RuntimeException("未绑定相应角色！");
        	request.setAttribute("authError", e);
        	return "../login";
        }
        response.sendRedirect(redirectUri);
        
        return null;
    }
    
    @RequestMapping("/captcha.do")
    public String createCaptchaImage(HttpServletRequest request,
                                     HttpServletResponse response) throws Exception {
        byte captchaChallengeAsJpeg[] = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        String captchaId = request.getSession().getId();
        BufferedImage challenge = jcaptchaService.getImageChallengeForID(captchaId, request.getLocale());
        ImageIO.write(challenge, "JPEG", jpegOutputStream);
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0L);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
        
        return null;
    }
}
